/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.adfmanager.wizards;


import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ResourceSelectionDialog;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;

import es.upm.dit.gsi.jadex.customproject.natures.JadexProjectNature;

/**
 * This page allows to get the following information in order to create the new agent
 *  - Agent name
 *    
 *  @author Pablo Muñoz
 *  @TODO verify if an agent with the same name is located in the workspace
 */

public class AgentWizardPage extends WizardPage {
	private Text agentNameText;
	private Text agentPackageText;
	private Text projectText;
	private Button browseButton;
	private ISelection selection;
	private IProject selectedProject;

	/**
	 * Constructor for AgentWizardPage
	 * 
	 * @param pageName
	 */
	public AgentWizardPage(ISelection selection) {
		super("wizardPage");
		setTitle("Agent Editor File");
		setDescription("This wizard creates a new agent file (with *.agent.xml extension)");
		this.selection = selection;
	}

	/**
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 3;
		layout.verticalSpacing = 9;
		
		Label label1 = new Label(container, SWT.NULL);
		label1.setText("Destination project: ");
		projectText = new Text(container, SWT.BORDER | SWT.SINGLE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		projectText.setLayoutData(gd);
		projectText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		projectText.setEditable(false);
		browseButton = new Button(container, SWT.PUSH);
		browseButton.setText("Browse...");
		browseButton.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e) {
				handleBrowse();
			}
		});
		
		Label separator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		separator.setLayoutData(gd);
		gd.horizontalSpan = 3;		
		
		Label label2 = new Label(container, SWT.NULL);
		label2.setText("Agent name:");
		agentNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		agentNameText.setLayoutData(gd);
		agentNameText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		
		Label label3 = new Label(container, SWT.NULL);
		label3.setText("Package:");
		agentPackageText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		agentPackageText.setLayoutData(gd);
		gd.horizontalSpan = 2;
		agentPackageText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		initialize();
		dialogChanged();
		setControl(container);
	}

	/**
	 * Tests if the current workbench selection is a suitable container to use.
	 */
	private void initialize() {
		agentNameText.setText("new_agent");
		
		if(selection != null && selection instanceof IStructuredSelection){
			Object element = ((IStructuredSelection)selection).getFirstElement();
			if(element instanceof IProject){
				IProject project = (IProject) element;
				try {
					if(project.hasNature(JadexProjectNature.NATURE_ID)){
						projectText.setText(project.getName());
						browseButton.setEnabled(false);
						selectedProject = project;
						return;
					}
				} catch (CoreException e) {
				}			
			}
						
		}
	}

	/**
	 * Ensures that the all text fields are set correctly.
	 */
	private void dialogChanged() {
		if(projectText.getText().length() == 0){
			updateStatus("A destination project for the new agent must be selected");
			return;
		}
		if (agentNameText.getText().length() == 0) {
			updateStatus("Agent name must be specified");
			return;
		}
		if (agentNameText.getText().replace('\\', '/').indexOf('/', 1) > 0) {
			updateStatus("Agent name must be valid");
			return;
		}
		updateStatus(null);
	}

	/*
	 * This method is called in order to update the status message 
	 */
	private void updateStatus(String message) {
		setErrorMessage(message);
		setPageComplete(message == null);
	}

	private void handleBrowse() {		
		ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
			    getShell(), new WorkbenchLabelProvider(), new BaseWorkbenchContentProvider());
			dialog.setTitle("Select tarjet Project");
			dialog.setMessage("Select the target project for the new agent:");
			dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
			dialog.setAllowMultiple(false);
			dialog.addFilter(new ViewerFilter() {				
				@Override
				public boolean select(Viewer viewer, Object parentElement, Object element) {
					if(element instanceof IProject){
						IProject p = (IProject) element;
						try{
							if(p.hasNature(JadexProjectNature.NATURE_ID)){
								return true;
							}
						}
						catch(CoreException e1){
							return false;
						}		
					}
					return false;
				}
			});		
		if (dialog.open() == ResourceSelectionDialog.OK) {
			Object[] result = dialog.getResult();
			IProject p = (IProject) result[0];
			projectText.setText(p.getName());
			selectedProject = p;
			dialogChanged();
		}
	}
	
	
	/**
	 * 
	 * @return the destination project for the new agent
	 */
	public IProject getSelectedProject(){
		return selectedProject;
	}
	
	/**
	 * 
	 * @return the agent name
	 */
	public String getAgentName(){
		return agentNameText.getText();
	}
	
	/**
	 * 
	 * @return the package for the new agent
	 */
	public String getAgentPackage(){
		return agentPackageText.getText();
	}
	
	/**
	 * 
	 * @return the name for the new agent file
	 */
	public String getFileName() {
		return agentNameText.getText() + ".agent.xml";
	}
}